package cn.edu.seu.herald.informationplatform.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import cn.edu.seu.herald.informationplatform.bean.league.LeagueInfo;
import cn.edu.seu.herald.informationplatform.bean.league.LeagueUser;
import cn.edu.seu.herald.informationplatform.bean.league.Vote;
import cn.edu.seu.herald.informationplatform.bean.league.VoteItem;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueInfoDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueUserDao;
import cn.edu.seu.herald.informationplatform.dao.database.VoteDataAccess;
import cn.edu.seu.herald.informationplatform.dao.database.VoteItemDataAccess;

public class VoteItemAdd extends HttpServlet {

	private static final String SUCCESS_MESSAGE = "操作成功";

	private static final String FAILURE_MESSAGE = "操作失败";

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	    //参数："itemName" "itemContent"
		//功能：添加名称为"itemName"、介绍内容为"itemContent"的选项，根据链接session获得leagueId
        //参考头像上传的servlet
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		int voteId = -1;
		String itemName = null;
		String itemContent = null;
		String relativeSavePath = null;
		try {
		LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
				  if (!isMultipart) {
				  System.out.println("File Not Uploaded");
				  } else {
				  FileItemFactory factory = new DiskFileItemFactory();
				  ServletFileUpload upload = new ServletFileUpload(factory);
				  List<?> items = null;
				  try {
				  items = upload.parseRequest(request);
				  System.out.println("items: "+items);
				  } catch (FileUploadException e) {
					  response.sendError(500, e.getMessage());
					  return;
				  }
				  Iterator<?> itr = items.iterator();
				  
				  while (itr.hasNext()) {		    
				  FileItem item = (FileItem) itr.next(); 
				     if(item.getFieldName().equals("voteId")){
				    	 System.out.println("HERE");
					      voteId = Integer.parseInt(item.getString(request.getCharacterEncoding()));
				      }
					  if(item.getFieldName().equals("itemName")){
						  itemName = item.getString(request.getCharacterEncoding());
					  }
					  if(item.getFieldName().equals("itemContent")){
						  itemContent = item.getString(request.getCharacterEncoding());
					  }
					  
						  if (!item.isFormField()&& item.getSize()!=0){
							  String picName = FilenameUtils.getName(item.getName());
							  
							  Random generator = new Random();
							  int r = Math.abs(generator.nextInt());

							  String reg = "[.*]";
							  String replacingtext = "";
							  
							  Pattern pattern = Pattern.compile(reg);
							  Matcher matcher = pattern.matcher(picName);
							  StringBuffer buffer = new StringBuffer();

							  while (matcher.find()) {
							  matcher.appendReplacement(buffer, replacingtext);
							  }
							  int IndexOf = picName.indexOf("."); 
							  String preFileName = picName.substring(IndexOf);
							  /*System.out.println("preFileName: "+preFileName);
				              System.out.println("fileName:" + buffer.toString());
				              System.out.println("fileType:" + item.getContentType());
				              System.out.println("fileSize:" + item.getSize() + "byte");*/
							  String finalimage = buffer.toString()+"_"+r+preFileName;
							  System.out.println("Final Image==="+finalimage);
							  String path = getServletContext().getRealPath("/");
							  Properties pro = System.getProperties();
						         String osName = pro.getProperty("os.name");
						         File saveFile = null;
						         String savePath = null;
						         
						         
						         if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
						        	 savePath = path+"/pictures/"+finalimage;
						        	 saveFile = new File(savePath); 
						        	
						         }
						         else{
						        	 savePath = path+"pictures\\"+finalimage;
						        	 saveFile = new File(savePath);
						         }
						         relativeSavePath = "pictures/"+finalimage;
						        
									item.write(saveFile);
								} 
							
							 
							 
							 /*String preRealPath = null;
						     File prefile = null;
						     if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
						    	 prefile = new File(preRealPath);  
						     }else{
						    	 prefile = new File(preRealPath.replaceAll("\\\\", "/"));
						     }
						     if (prefile.isFile() && prefile.exists()) {  
						    	 prefile.delete();  
							 }  */
						   
						  }
					  
				  /*String name = item.getFieldName();
				  System.out.println("name: "+name);
				  String value = item.getString();
				  System.out.println("value: "+value);*/
				  }

				  VoteItem voteItem = new VoteItem();
				  VoteDataAccess voteDataAccess = VoteDataAccess.getInstance();
				  Vote vote = voteDataAccess.getVoteById(voteId);
				  voteItem.setVote(vote);
				  voteItem.setName(itemName);
				  voteItem.setContent(itemContent);
				  voteItem.setPicture(relativeSavePath);
				  VoteItemDataAccess voteItemDataAccess = VoteItemDataAccess.getInstance();			  
				  voteItemDataAccess.createNewVoteItem(voteItem);
				response.sendRedirect("./polling.jsp?league="+luSessionCookieAccess.getLeagueId());
			} catch (Exception e) {
				e.printStackTrace();
				  return;
			}
	}
	}

